
#include "JsonParse.h"
#include "global.h"
#include "ActionCtrl.h"
#include  "blefunc.h"

bool parseLocalConfig(JsonDocument localConfig)
{

    // deleteGlobalLocalConfig();


    LocalConfig *localConfigObj = getGlobalLocalConfig();
    if(localConfig.containsKey("beep")){
        String beep= localConfig["beep"];
        localConfigObj->setBeep(beep.equals("1"));
    }

    if(localConfig.containsKey("indicatorLight")){
        
        String indcatorLight= localConfig["indicatorLight"];
        localConfigObj->setIndicatorLight(indcatorLight.equals("1"));

        printStr("light->",getGlobalLocalConfig()->getIndicatorLight());

        
    }




    // setGlobalLocalConfig(localConfigObj);

    return true;
}


bool parseTypeConfig(String typeConfigStr){

 if (typeConfigStr == nullptr || typeConfigStr.isEmpty())
    {
        Serial.println("typeConfigStr == null");
        return false;
    }

    printStr("typeConfigStr------------------");
    printStr(typeConfigStr);
    JsonDocument typeConfig;
    DeserializationError error1 = deserializeJson(typeConfig, typeConfigStr);
    if (error1)
    {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error1.f_str());
        return false;
    }
 
        String frequency_daytime = typeConfig["frequency_daytime"];
        String frequency_night = typeConfig["frequency_night"];
        String startTime = typeConfig["startTime"];
        String endTime = typeConfig["endTime"];
        String runMode = typeConfig["runMode"];
        String wakeupInterval_daytime = typeConfig["wakeupInterval_daytime"];


        String wakeupInterval_night = typeConfig["wakeupInterval_night"];

        bool updateFirmware = typeConfig["forceUpgrade"];
        String version = typeConfig["firmwareVersionCode"];
        String name = typeConfig["firmwareVersionName"];
        String firmwareUrl = typeConfig["firmwareUrl"];

        

        TypeConfig *typeConfigObject = getGlobalLocalConfig()->getTypeConfig();
      
        typeConfigObject->setEndTime(endTime);
        typeConfigObject->setStartTime(startTime);
        typeConfigObject->setFrequencyDaytime(frequency_daytime);
        typeConfigObject->setFrequencyNighttime(frequency_night);

        typeConfigObject->setFrequencyDaytime(frequency_daytime);
        typeConfigObject->setFrequencyNighttime(frequency_night);

        if(!isStringEmpty(runMode)){
      
            typeConfigObject->setRunMode(runMode.toInt());
        }
        
        typeConfigObject->setUpdateFirmware(updateFirmware);
        typeConfigObject->setVersion(version);
        typeConfigObject->setFirmwareUrl(firmwareUrl);
        typeConfigObject->setVersionName(name);
        typeConfigObject->setWakeupInterval_Daytime(wakeupInterval_daytime);
        typeConfigObject->setWakeupInterval_Night(wakeupInterval_night);

        //typeConfigObject->setWakeupInterval_Daytime("60");//这里是测试
        //typeConfigObject->setWakeupInterval_Night("60");//这里是测试，不要忘记注释
        //  localConfigObj->setTypeConfig(typeConfigObject);

    return true;
}

bool parseBTDevice(String btDeviceStr){
       if (btDeviceStr == nullptr || btDeviceStr.isEmpty())
    {
        Serial.println("btDeviceStr == null");
        return false;
    }
    JsonDocument btDevice;
    DeserializationError error1 = deserializeJson(btDevice, btDeviceStr);
    if (error1)
    {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error1.f_str());
        return false;
    }
    
   JsonArray  jsonArray =  btDevice.as<JsonArray>();

   for (size_t i = 0; i < jsonArray.size(); i++)
   {
        BTDevice*  device = new BTDevice();
        device->address = jsonArray[i]["address"].as<String>();
        device->name = jsonArray[i]["name"].as<String>();
        device->deviceId = jsonArray[i]["deviceId"].as<String>();
        device->nickName = jsonArray[i]["nickName"].as<String>();
        RemoteBle* remoteBle = new RemoteBle(device);
        printStr("蓝牙设备添加到Map",device->address);

     
        getRemoteBleMap()->put(convertToUpperCaseMacAddress(device->address.c_str()),remoteBle);   
   }


   return true;
   
  
  



}


bool parseConfig(String configStr){
    if (configStr == nullptr || configStr.isEmpty())
    {
        Serial.println("configStr == null");
        return false;
    }
    JsonDocument config;
    DeserializationError error1 = deserializeJson(config, configStr);
    if (error1)
    {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error1.f_str());
        return false;
    }

  if(config.containsKey("bindBTDeviceList")){
        String bt =  config["bindBTDeviceList"].as<String>();
        printStr(bt);

       if(parseBTDevice(bt)){
          //  putPreferenceString("localConfig", config["localConfig"]);
          printStr("bindBTDeviceList 解析成功");
       }else{
          printStr("bindBTDeviceList 解析失败");
          return false;
       } 
    }

    if(config.containsKey("localConfig")){
       if(parseLocalConfig(config["localConfig"])){
          //  putPreferenceString("localConfig", config["localConfig"]);
            printStr("localConfig 解析成功");
       }else{
          printStr("localConfig 解析失败");
          return false;
       } 
    }



    if(config.containsKey("typeConfig")){
        if( parseTypeConfig(config["typeConfig"])){
            //  putPreferenceString("typeConfig", config["localConfig"]);
            printStr("typeConfig 解析成功");
        }else{
             printStr("typeConfig 解析失败");
             return false;
        }
    }

   
    

  return true;
   

}

bool parseLocalConfigString(String localConfig)
{
    if (localConfig == nullptr || localConfig.isEmpty())
    {
        Serial.println("localConfig == null");
        return false;
    }

    printStr("localconfig------------------");
    printStr(localConfig);
    JsonDocument doc2;
    DeserializationError error1 = deserializeJson(doc2, localConfig);
    if (error1)
    {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error1.f_str());
        return false;
    }

    return parseLocalConfig(doc2);
}

// 解析json并保存在内存
bool parseTimerActionString(String timerAction)
{

    if (timerAction != NULL)
    {
        JsonDocument doc1;
        DeserializationError error = deserializeJson(doc1, timerAction);
        if (error)
        {
            Serial.print(F("deserializeJson() failed: "));
            Serial.println(error.f_str());
            return false;
        }
        return parseTimerAction(doc1);
    }
    Serial.println("timerAction == null");
    return false;
}

bool parseTimerAction(JsonDocument timerAction)
{

    const char *deviceId = timerAction["deviceId"];
    TimerAction *ta = new TimerAction(deviceId);
    // 解析weekItems
    for (int i = 0; i < 7; i++)
    {
        const JsonObject &weekItem = timerAction["weekItems"][i];
        DayItem di;
        di.on = weekItem["on"];
        di.weekNumber = weekItem["weekNumber"];
        // 解析actions
        JsonArray actions = weekItem["actions"];
        for (size_t i = 0; i < actions.size(); i++)
        {
            TimerActionA *actionsItem = new TimerActionA();

            actionsItem->index = i;
            JsonObject jsonActionItem = actions[i];
            actionsItem->actionTime = jsonActionItem["actionTime"].as<String>();
            actionsItem->duration = jsonActionItem["duration"].as<String>();
            actionsItem->on = jsonActionItem["on"];
            Action *a = new Action();
            JsonObject action = actions[i]["action"];
            a->id = action["id"].as<String>();
            a->on = action["on"];
             if(action.containsKey("name")){
            a->name=action["name"].as<String>();
        }
            actionsItem->action = a;
            di.addAction(actionsItem);
        }
        ta->weekItems[i] = di;
    }

    // // 解析intervalTimerAction;
    JsonArray intervalTimerAction = timerAction["intervalTimerAction"];
    for (size_t i = 0; i < intervalTimerAction.size(); i++)
    {
        TimerActionB *actionsItem = new TimerActionB();
        actionsItem->setIndex(i);
        JsonObject jsonActionItem = intervalTimerAction[i];
        actionsItem->intervalTime = jsonActionItem["intervalTime"].as<String>();
        actionsItem->duration = jsonActionItem["duration"].as<String>();
        actionsItem->on = jsonActionItem["on"];
        Action *a = new Action();
        JsonObject action = intervalTimerAction[i]["action"];
        a->id = action["id"].as<String>();
        a->on = action["on"];
        if(action.containsKey("name")){
            a->name=action["name"].as<String>();
        }
        
        actionsItem->action = a;
        ta->addIntervalTimerAction(actionsItem);
    }

    // 解析singleTimerAction;
    JsonArray singleTimerAction = timerAction["singleTimerAction"];
    for (size_t i = 0; i < singleTimerAction.size(); i++)
    {
        TimerActionA *actionsItem = new TimerActionA();
        JsonObject jsonActionItem = singleTimerAction[i];
        actionsItem->actionTime = jsonActionItem["actionTime"].as<String>();
        actionsItem->duration = jsonActionItem["duration"].as<String>();
        actionsItem->on = jsonActionItem["on"];

        Action *a = new Action();
        JsonObject action = singleTimerAction[i]["action"];
        a->id = action["id"].as<String>();
        a->on = action["on"];
         if(action.containsKey("name")){
            a->name=action["name"].as<String>();
        }
        actionsItem->action = a;
        ta->addSingleTimerAction(actionsItem);
    }

    deleteGlobalTimerAction();
    setGlobalTimerAction(ta);
    // 这后面一定要加返回值，不然会崩溃！！！！！切记，坑
    return true;
}

// 假设你的类定义和构造函数保持不变（如上面的代码所示）

// 辅助函数，用于打印String数组
void printStringArray(String arr[], int count)
{
    for (int i = 0; i < count; i++)
    {
        Serial.print("Element ");
        Serial.print(i);
        Serial.print(": ");
        Serial.println(arr[i]);
    }
}

// 辅助函数，用于打印TimerActionA数组
void printTimerActionAArray(TimerActionA *arr[], int count)
{
    for (int i = 0; i < count; i++)
    {
        if (arr[i] != nullptr)
        {
            Serial.print("TimerActionA ");
            Serial.print(i);
            Serial.println(":");
            Serial.print("  actionTime: ");
            Serial.println(arr[i]->actionTime);
            Serial.print("  duration: ");
            Serial.println(arr[i]->duration);
            Serial.print("  action->id: ");
            if (arr[i]->action != nullptr)
            {
                Serial.println(arr[i]->action->id);
            }
            else
            {
                Serial.println("nullptr");
            }
            Serial.print("  on: ");
            Serial.println(arr[i]->on);
        }
        else
        {
            Serial.print("TimerActionA ");
            Serial.print(i);
            Serial.println(" is nullptr");
        }
    }
}

// 辅助函数，用于打印TimerActionB数组
void printTimerActionBArray(TimerActionB *arr[], int count)
{
    for (int i = 0; i < count; i++)
    {
        if (arr[i] != nullptr)
        {
            Serial.print("TimerActionB ");
            Serial.print(i);
            Serial.println(":");
            Serial.print("  intervalTime: ");
            Serial.println(arr[i]->intervalTime);
            Serial.print("  duration: ");
            Serial.println(arr[i]->duration);
            Serial.print("  action->id: ");
            if (arr[i]->action != nullptr)
            {
                Serial.println(arr[i]->action->id);
            }
            else
            {
                Serial.println("nullptr");
            }
            Serial.print("  on: ");
            Serial.println(arr[i]->on);
        }
        else
        {
            Serial.print("TimerActionB ");
            Serial.print(i);
            Serial.println(" is nullptr");
        }
    }
}

// 辅助函数，用于打印DayItem数组
void printDayItemArray(DayItem arr[], int count)
{
    for (int i = 0; i < count; i++)
    {
        Serial.print("DayItem ");
        Serial.print(i);
        Serial.println(":");
        Serial.print("  on: ");
        Serial.println(arr[i].on);
        Serial.print("  weekNumber: ");
        Serial.println(arr[i].weekNumber);
        Serial.print("  actionCount: ");
        Serial.println(arr[i].actionCount);
        printTimerActionAArray(arr[i].actions, arr[i].actionCount);
    }
}

// 打印TimerAction对象
void printTimerAction(TimerAction &timerAction)
{
    Serial.println("TimerAction:");
    Serial.print("  deviceId: ");
    Serial.println(timerAction.deviceId);
    Serial.print("  singleActionCount: ");
    Serial.println(timerAction.singleActionCount);
    printTimerActionAArray(timerAction.singleTimerAction, timerAction.singleActionCount);
    Serial.print("  intervalActionCount: ");
    Serial.println(timerAction.intervalActionCount);
    printTimerActionBArray(timerAction.intervalTimerAction, timerAction.intervalActionCount);
    printDayItemArray(timerAction.weekItems, 7);
}

void setLocalUpgrade(bool b)
{
    String localConfig = getPreferenceString("localConfig");

    Serial.println(localConfig);
    JsonDocument doc;
    DeserializationError error = deserializeJson(doc, localConfig);
    if (error)
    {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error.f_str());
        return;
    }
    String forceUpgrade = doc["typeConfig"]["forceUpgrade"];
    Serial.println("forceUpgrade");
    Serial.println(forceUpgrade);
    doc["typeConfig"]["forceUpgrade"] = b;

    char jsonStr[2048];

    serializeJson(doc, jsonStr);

    Serial.println(jsonStr);
    putPreferenceString("localConfig", jsonStr);

    //      // JSON字符串
    //   const char* jsonStr = "{\"typeConfig\": \"{\\\"endTime\\\":\\\"18:00\\\",\\\"firmwareUrl\\\":\\\"http://www.smartlinked.cn/firmware/firmware_1.0.1.bin\\\",\\\"firmwareVersionCode\\\":\\\"4\\\",\\\"firmwareVersionName\\\":\\\"firmware_1.0.1.bin\\\",\\\"forceUpgrade\\\":true,\\\"frequency_daytime\\\":180,\\\"frequency_night\\\":180,\\\"nowFrequency\\\":180,\\\"runMode\\\":3,\\\"startTime\\\":\\\"08:00\\\"}\"}";

    //   // 创建一个StaticJsonDocument（根据JSON字符串的大小选择合适的大小）
    //   StaticJsonDocument<2048> doc;

    //   // 解析JSON字符串
    //   DeserializationError error = deserializeJson(doc, jsonStr);
    //   if (error) {
    //     Serial.print(F("deserializeJson() failed: "));
    //     Serial.println(error.f_str());
    //     return;
    //   }

    //   // 获取嵌套在typeConfig中的JSON对象
    //   const char* typeConfigStr = doc["typeConfig"];
    //   if (!typeConfigStr) {
    //     Serial.println("typeConfig not found");
    //     return;
    //   }

    //   // 解析嵌套的JSON对象
    //   StaticJsonDocument<1024> nestedDoc;
    //   DeserializationError nestedError = deserializeJson(nestedDoc, typeConfigStr);
    //   if (nestedError) {
    //     Serial.print(F("deserializeJson(nested) failed: "));
    //     Serial.println(nestedError.f_str());
    //     return;
    //   }

    //   // 修改forceUpgrade字段
    //   nestedDoc["forceUpgrade"] = false; // 设置为false，你可以根据需要更改为true

    //   // 序列化修改后的嵌套JSON对象
    //   String modifiedTypeConfig;
    //   serializeJson(nestedDoc, modifiedTypeConfig);

    //   // 更新原始JSON字符串中的typeConfig字段
    //   char modifiedJsonStr[4096]; // 确保有足够的空间来存储整个字符串
    //   snprintf(modifiedJsonStr, sizeof(modifiedJsonStr), "{\"typeConfig\":%s}", modifiedTypeConfig.c_str());

    //   // 打印修改后的JSON字符串
    //   Serial.println(modifiedJsonStr);
}